package org.jf.tool.fx.jftoolfx.tools.cron.controller;

import com.alibaba.fastjson2.util.DateUtils;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Spinner;
import javafx.scene.control.ToggleGroup;

import java.net.URL;
import java.util.*;

/**
 * cron 工具
 *
 * @author jifeng_zhang
 * @date 2025/10/9 上午11:41
 */
public class YearController extends CronController {

    @FXML
    private ToggleGroup typeToggleGroup;
    @FXML
    private Spinner<Integer> periodBegin;
    @FXML
    private Spinner<Integer> periodEnd;

    private CronController cronController;

    @Override
    protected void init(URL url, ResourceBundle resourceBundle) {
        // 获取当前年
        int year = Calendar.getInstance().get(Calendar.YEAR);
        periodBegin.getValueFactory().setValue(year);
        periodEnd.getValueFactory().setValue(year + 10);
        // 添加值改变监听器（推荐方式）
        periodBegin.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue >= periodEnd.getValue()) {
                periodBegin.getValueFactory().setValue(periodEnd.getValue() - 1);
            }
            typeCheck();
        });
        periodEnd.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue <= periodBegin.getValue()) {
                periodEnd.getValueFactory().setValue(periodBegin.getValue() + 1);
            }
            typeCheck();
        });
    }

    public void setCronController(CronController cronController) {
        this.cronController = cronController;
    }

    public void typeCheck() {
        String type = typeToggleGroup.getSelectedToggle().getUserData().toString();
        switch (type) {
            case "no":
                cronController.cronYearText.setText("");
                break;
            case "year":
                cronController.cronYearText.setText("*");
                break;
            case "period":
                int periodBeginValue = periodBegin.getValue();
                int periodEndValue = periodEnd.getValue();
                cronController.cronYearText.setText(periodBeginValue + "-" + periodEndValue);
                break;
        }
        cronController.cronText.setText(cronController.cronSecondText.getText() + " " + cronController.cronMinuteText.getText() + " " + cronController.cronHourText.getText() + " " + cronController.cronDayText.getText() + " " + cronController.cronMonthText.getText() + " " + cronController.cronWeekText.getText() + " " + cronController.cronYearText.getText());
        cronController.resultText.setText("");
    }
}
